const express = require('express');
const path = require('path');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const connectDB = require('./config/db');
const logger = require('./utils/logger');
const { notFound, errorHandler } = require('./middlewares/error');
const config = require('./config/default');

// 引入路由
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const productRoutes = require('./routes/productRoutes');
const teamRoutes = require('./routes/teamRoutes');
const fileRoutes = require('./routes/fileRoutes');
const settingRoutes = require('./routes/settingRoutes');
const dashboardRoutes = require('./routes/dashboardRoutes');

// 初始化Express应用
const app = express();

// 连接数据库
connectDB();

// 中间件
app.use(cors({
  origin: 'http://localhost:5173', // 前端开发服务器地址
  credentials: true // 允许跨域请求携带凭证
}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser()); // 添加cookie解析器中间件

// 静态文件服务 - 用于提供上传的文件
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
app.use('/api/teams', teamRoutes);
app.use('/api/files', fileRoutes);
app.use('/api/settings', settingRoutes);
app.use('/api/dashboard', dashboardRoutes);

// 基础API信息路由
app.get('/api', (req, res) => {
  res.json({
    message: '企业后台管理系统API服务',
    version: '1.0.0',
    endpoints: [
      '/api/auth',
      '/api/users',
      '/api/products',
      '/api/teams',
      '/api/files',
      '/api/settings',
      '/api/dashboard'
    ]
  });
});

// 根路由 - 健康检查
app.get('/', (req, res) => {
  res.json({ 
    status: 'online',
    message: '企业后台管理系统API服务正在运行',
    time: new Date().toISOString()
  });
});

// 错误处理中间件
app.use(notFound);
app.use(errorHandler);

// 启动服务器
const PORT = config.port;
app.listen(PORT, () => {
  logger.info(`服务器已在端口 ${PORT} 上启动`);
  logger.info(`环境: ${config.environment}`);
  logger.info(`API 地址: http://localhost:${PORT}/api`);
});

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  logger.error(`未捕获的异常: ${err.message}`);
  console.error(err);
  process.exit(1);
});

// 处理未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
  logger.error(`未处理的Promise拒绝: ${reason}`);
  console.error(reason);
});

module.exports = app; 